cc.Class({
    extends: cc.Component,

    properties: {        
        numLayoutPrefab: cc.Prefab,
        allLayoutNode: cc.Node,
        editNode: cc.Node,
        rollTime: 2,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        // 预制池
        this.prefabPool = new cc.NodePool();
        // 预制数组，方便管理
        this.prefabArray = [];
        // 获取每个数字长度，用于获取y坐标
        let numLayout = cc.instantiate(this.numLayoutPrefab);
        this.eachHeight = numLayout.height / 11;
        this.prefabPool.put(numLayout);
    },

    getNumStr () {
        // 获取编辑框中输入的数字(字符串)
        let numStr = this.editNode.getComponent(cc.EditBox).string;
        return numStr;
    },

    okBtn () {
        // 删除节点
        this.allLayoutNode.removeAllChildren();

        // 恢复坐标，回收预制，清空数组
        for(let i=0; i<this.prefabArray.length; i++) {
            this.prefabArray[i].setPosition(0, 0);
            this.prefabPool.put(this.prefabArray[i]);
        }
        this.prefabArray = [];

        // 首先获取数字(字符串)
        let numStr = this.getNumStr();
        
        // 再判断是否可以转换为数字
        let num = Number(numStr);
        if (!isNaN(num)) {
            // 根据numStr长度生成相应数量的预制
            for(let i=0; i<numStr.length; i++) {
                // 将生成的预制放入数组中
                this.prefabArray.push(this.getNewPrefab());
            }
            // 滚动
            for(let i=0; i<numStr.length; i++) {
                this.roll(numStr[i], this.prefabArray[i])
            }
        }
        else {
            console.log('非数字！');
        }
    },

    getNewPrefab () {
        // 生成预制
        let numLayout = null;
        // 根据节点池大小判断是从预制池中获取还是新生成一个
        if (this.prefabPool.size() > 0) 
            numLayout = this.prefabPool.get();
        else 
            numLayout = cc.instantiate(this.numLayoutPrefab);
        // 添加到总布局中
        this.allLayoutNode.addChild(numLayout);
        return numLayout;
    },

    roll (num, prefab) {
        // 关键是获取y坐标
        let y = null;

        if (num != '.') 
            y = (Number(num)-5)*this.eachHeight;
        else 
            y = (10-5)*this.eachHeight;

        let moveTo = cc.moveTo(this.rollTime, cc.v2(0, y)).easing(cc.easeCubicActionOut());
        prefab.runAction(moveTo);
    }

});
